<?php
    // +----------------------------------------------------------------------
    // | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ] 
    // +----------------------------------------------------------------------
    // | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
    // +----------------------------------------------------------------------
    // | SiteUrl: http://www.luckyhhy.cn
    // +----------------------------------------------------------------------
    // | Author: LuckyHhy <jackhhy520@qq.com>
    // +----------------------------------------------------------------------
    // | Date: 2020/3/19-10:35
    // +----------------------------------------------------------------------
    // | Description:  
    // +----------------------------------------------------------------------

    namespace app\wechat\controller;

    use app\common\controller\BaseController;
    use EasyWeChat\Kernel\Messages\Text;
    use EasyWeChat\Kernel\Messages\Article;
    use EasyWeChat\Kernel\Messages\Image;
    use EasyWeChat\Kernel\Messages\Video;
    use EasyWeChat\Kernel\Messages\Voice;
    use EasyWeChat\Kernel\Messages\News;
    use EasyWeChat\Kernel\Messages\NewsItem;

    use app\wechat\model\WxFans;
    use app\wechat\model\WxMaterial;
    use app\wechat\model\WxMaterialInfo;
    use app\wechat\model\WxMsgHistory;
    use app\wechat\model\WxReply;
    use app\wechat\model\WxTag;

    use think\Db;
    use think\Exception;
    use think\facade\Request;
    use think\facade\View;
    use app\wechat\model\WxAccount;

    use app\wechat\service\WechatApp;


    /**
     * Class Wechat
     * @package app\wechat\controller
     */
    class Wechat extends BaseController
    {



        /**
         * @var array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:03
         * //图片（image）: 2M，支持bmp/png/jpeg/jpg/gif格式
         */
        protected $imageValidate = [
            'image' => 'filesize:2048|fileExt:jpg,png,gif,jpeg',

        ];
        /**
         * @var array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         *  //视频（video）：10MB，支持MP4格式
         */
        protected $videoValidate = [
            'file' => 'filesize:10240|fileExt:avi,rmvb,3gp,flv,mp4,rm',

        ];
        /**
         * @var array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         *  //语音（voice）：2M，播放长度不超过60s，mp3/wma/wav/amr格式
         */
        protected $voiceValidate = [
            'file' => 'filesize:2048|fileExt:mp3,wma,wav,amr',

        ];
        /**
         * @var array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         *  //缩略图（thumb）：64KB，支持JPG格式
         */
        protected $thumbValidate = [
            'image' => 'filesize:64|fileExt:jpg',

        ];
        /**
         * @var array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         */
        protected $where = [];
        /**
         * @var
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         */
        public $wechatApp;
        /**
         * @var
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         */
        public $store_id;
        /**
         * @var
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         */
        protected $wechatAccount;
        /**
         * @var array
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20-17:04
         */
        protected $materialType = ['news', 'video', 'voice', 'image', 'music'];

        /**
         * @throws Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: initialize
         * @describe:
         */
        public function initialize()
        {
            parent::initialize(); // TODO: Change the autogenerated
            $wechatApp           = new WechatApp();
            $this->store_id      = $wechatApp->store_id;
            $this->wechatAccount = WxAccount::where('status', 1)->where('store_id', $this->store_id)->find();

            if ($this->wechatAccount) {
                $this->wechatApp = cache('wechatapp_'.$this->wechatAccount->id);
                if (!$this->wechatApp) {
                    $this->wechatApp = $wechatApp->wechatApp;
                }
                $this->where = ['store_id' => $this->store_id, 'wx_aid' => $this->wechatAccount->id];

            } else {
                $this->wechatAccount = WxAccount::where('store_id', $this->store_id)->find();
            }
        }



        /**
         ************************公众号管理****************************
         */
        /**
         * @return array|mixed
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: index
         * @describe:
         */
        public function index()
        {
            if (Request::isPost()) {
                $list = Db::name('wx_account')->alias('a')
                    ->leftJoin('wx_type t', 't.type_id=a.type')
                    ->field('a.*,t.name as type_name')->select();
                return $result = ['code' => 0, 'msg' => 'ok', 'data' => $list,'count'=>count($list)];
            }
            return $this->fetch();
        }

        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: add
         * @describe: 添加账号
         */
        public function add()
        {
            if (IS_POST) {
                $data = Request::post();
                $va   = new \app\wechat\validate\WxAccount();
                if (!$va->check($data)) {
                    $this->error($va->getError());
                }
                try{
                    if (!isset($data['id'])) {
                        $data['weixin'] = $data['wxname'];
                        $res            = WxAccount::create($data);
                    } else {
                        $res = WxAccount::update($data);
                    }
                    if ($res) {
                        $this->success("操作成功");
                    } else {
                        $this->error("操作失败");
                    }
                }catch (Exception $exception){
                    $this->error($exception->getMessage());
                }
            }
            $view = [
                'info' => '',
            ];
            View::assign($view);

            return view();
        }



        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: edit
         * @describe: 编辑账号
         */
        public function edit()
        {
            $info = WxAccount::find(Request::param('id/d'));
            $view = [
                'info' => $info,
            ];
            View::assign($view);

            return view('add');
        }

        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: state
         * @describe: 修改状态
         */
        public function state()
        {
            $id = Request::post('id');
            if ($id) {
                $info         = WxAccount::find($id);
                $info->status = $info->status == 1 ? 0 : 1;
                if ($info->status == 1) {
                    $list = WxAccount::where('status', 1)->where('id', '<>', $info->id)->select();
                    if ($list) {
                        foreach ($list as $k => $v) {
                            $v->status = 0;
                            $v->save();
                        }
                    }
                }
                $info->save();
                $this->success("修改成功");
            } else {
                $this->error('非法数据');
            }
        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: delete
         * @describe: 删除
         */
        public function delete()
        {
            $id = Request::post('id');
            if ($id) {
                WxAccount::destroy($id);
                $this->success("删除成功");
            } else {
                $this->error('非法数据');
            }
        }







        /**
         ************************菜单管理****************************
         */


        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: menu
         * @describe:
         */
        public function menu()
        {
            return view();
        }



        /**
         * @return array|\PDOStatement|string|\think\Collection
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: getWxAccount
         * @describe: 获取账号列表
         */
        public function getWxAccount()
        {
            $info = WxAccount::order('status desc')->select();
            return $info;
        }



        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: changeApp
         * @describe:更改app
         */
        public function changeApp()
        {
            $appid            = Request::post('app_id');
            $isAPP            = WxAccount::where('app_id', $appid)->value('status');
            $button['button'] = [];
            if (!$isAPP) {
                $this->error('失败', '', $button);
            }
            //获取当前菜单
            $menu = cache('wx_menus');
            if (!$menu) {
                $menu = $this->wechatApp->menu->list();
                cache('wx_menus', $menu);
            }
            if (isset($menu['menu'])) {

                $button = $menu['menu'];
                $this->success('成功', '', $button);
            } else {
                $this->error('失败', '', $button);
            }

        }


        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: addWeixinMenu
         * @describe:添加微信菜单
         */
        public function addWeixinMenu()
        {
            $data   = Request::post();
            $app_id = $data['app_id'];
            $isApp  = WxAccount::where('store_id', $this->store_id)->cache(3600)->where('app_id', $app_id)->value(
                'status'
            );
            if ($isApp != 1) {
                $this->error("账号授权错误");
            }
            $menu = $data['menu'];
            if (!empty($menu)) {
                $res = $this->wechatApp->menu->create($menu['button']);
                if ($res['errcode'] == 0) {
                    $this->success("添加成功");

                } else {
                    $this->error($res['errmsg']);
                }
            }
            $this->error("添加失败");
        }



        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: updataWechatMenu
         * @describe: 更新菜单
         */
        public function updataWechatMenu()
        {
            $menu = $this->wechatApp->menu->list();
            $this->success("操作成功");

        }



        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: menuDel
         * @describe: 删除菜单
         */
        public function menuDel()
        {
            $res = $this->wechatApp->menu->delete(); // 全部
            if ($res['errcode'] == 0) {
                $this->success("删除成功");
            } else {
                $this->error("删除失败");
            }
        }






        /**
         ************************粉丝管理***************************
         */
        /**
         * @return array|\think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: fans
         * @describe: 粉丝列表
         */
        public function fans()
        {

            if (Request::isPost()) {
                $wx_aid = Request::post('wx_aid');
                if (!$wx_aid) {
                    $wx_aid = $this->wechatAccount->id;
                }
                if (!$wx_aid) {
                    return $result = ['code' => 0, 'msg' => "账号授权错误"];
                }
                $keys  = Request::post('keys', '', 'trim');
                $page  = Request::post('page') ? Request::post('page') : 1;
                $limit = Request::post('limit') ? Request::post('limit') : 10;
                $list  = WxFans::where('nickname', 'like', '%'.$keys.'%')->where('wx_aid', $wx_aid)->order(
                    'fans_id desc'
                )->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

                return $result = [
                    'code'  => 0,
                    'msg'   => 'ok',
                    'data'  => $list['data'],
                    'count' => $list['total'],
                ];
            }
            $wxAccount = WxAccount:: where('store_id', $this->store_id)->select();
            $view      = [
                'title'     => '粉丝',
                'info'      => '',
                'wxAccount' => $wxAccount,
            ];
            View::assign($view);

            return view();
        }


        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: fansAysn
         * @describe: 同步粉丝
         */
        public function fansAysn()
        {
            $wx_aid = Request::post('wx_aid');
            if (!$wx_aid) {
                $this->error('请求错误');
            }
            $wxAccount = $this->wechatAccount;
            if (!$wxAccount) {
                $this->error("账号授权错误");
            }
            $usersOpenidList = $this->wechatApp->user->list();
            $users           = [];
            if ($usersOpenidList['total'] > 0) {
                foreach ($usersOpenidList['data']['openid'] as $k => $v) {
                    $users[$k] = $this->wechatApp->user->get($v);
                }
            }
            $WxFansModel = new WxFans();

            foreach ($users as $k => $v) {
                $v['wx_aid']     = $wx_aid;
                $v['tagid_list'] = json_encode($v['tagid_list']);

                $fans = $WxFansModel::where($this->where)->cache(30)->where('openid', $v['openid'])->find();
                if ($fans) {
                    $v['update_time'] = time();
                    $res              = $fans->force()->save($v);
                } else {
                    $v['store_id']        = $this->store_id;
                    $v['update_time']     = time();
                    $v['nickname_encode'] = json_encode($v['nickname']);
                    $res                  = $WxFansModel::create($v);
                }
            }

            $this->success('同步成功');
        }



        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: fansTagGroup
         * @describe:粉丝标签
         */
        public function fansTagGroup()
        {
            if (Request::isPost()) {
                $id     = Request::post('id');
                $tag    = Request::post('tag');
                $wxFans = WxFans::where('fans_id', $id)->find();

                $tags        = WxTag::where('store_id', $this->store_id)->where('wx_aid', $wxFans->wx_aid)->find();
                $wxFans->tag = $tag;
                $res         = $this->wechatApp->user_tag->tagUsers([$wxFans->openid], $tags['tag_id']);
                if ($res) {
                    $wxFans->save();
                    $this->success("操作成功");
                } else {
                    $this->error("操作失败");

                }
            }

        }



        /**
         * @return array|\think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: tag
         * @describe:粉丝标签管理
         */
        public function tag()
        {
            if (Request::isPost()) {
                $wx_aid = Request::post('wx_aid');
                if (!$wx_aid) {
                    $wx_aid = $this->wechatAccount->id;
                }
                if (!$wx_aid) {
                    return $result = ['code' => 0, 'msg' => "账号授权错误"];

                }
                $keys  = Request::post('keys', '', 'trim');
                $page  = Request::post('page') ? Request::post('page') : 1;
                $limit = Request::post('limit') ? Request::post('limit') : 10;
                $list  = Db::name('wx_tag')->where('name', 'like', '%'.$keys.'%')->where('wx_aid', $wx_aid)->order(
                    'id desc'
                )->paginate(['list_rows' => $limit, 'page' => $page])->toArray();

                return $result = [
                    'code'  => 0,
                    'msg'   => 'oj',
                    'data'  => $list['data'],
                    'count' => $list['total'],
                ];
            }

            $wxaccount = WxAccount::where('store_id', $this->store_id)->cache(3600)->select();

            $view = ['title' => lang('tag'), 'info' => '', 'wxaccount' => $wxaccount];
            View::assign($view);

            return view();

        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: tagState
         * @describe: 修改状态
         */
        public function tagState()
        {
            if (Request::isPost()) {
                $id = Request::post('id');
                if (empty($id)) {
                    $this->error("id 错误");
                }
                $adv         = WxTag::find($id);
                $status      = $adv['status'] == 1 ? 0 : 1;
                $adv->status = $status;
                $adv->save();
                $this->success("操作成功");
            }

        }



        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: tagAysn
         * @describe: 同步标签
         */
        public function tagAysn()
        {
            if (Request::isPost()) {
                $wx_aid = $this->wechatAccount->id;
                try {
                    $tags = $this->wechatApp->user_tag->list();
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }

                if (empty($tags['tags'])) {
                    $this->error("暂无数据");
                }
                foreach ($tags['tags'] as $k => $v) {
                    $info        = WxTag::where('name', $v['name'])->find();
                    $v['tag_id'] = $v['id'];

                    if (!$info) {
                        $v['store_id'] = $this->store_id;
                        $v['wx_aid']   = Request::post('wx_aid') ? Request::post('wx_aid') : $wx_aid;
                        unset($v['id']);
                        WxTag::create($v);
                    } else {
                        $v['id'] = $info['id'];
                        WxTag::update($v);
                    }
                }
                $this->success("操作成功");
            }
            $this->error("操作失败");
        }



        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: tagAdd
         * @describe: 添加标签
         */
        public function tagAdd()
        {
            if (Request::isPost()) {
                $data = Request::post();
                try {
                    $data['store_id'] = $this->store_id;
                    $validate         = new \app\wechat\validate\WxTag();
                    if (!$validate->check($data)) {
                        $this->error($validate->getError());
                    }
                    if (isset($data['id']) && is_numeric((int)$data['id'])) {
                        $tag = WxTag::find($data['id']);

                        $res = $this->wechatApp->user_tag->update($tag['tag_id'], $data['name']);

                        if ($res['errcode'] == 0) {
                            WxTag::update($data);
                            $this->success("编辑成功");
                        } else {
                            $this->error("编辑失败");
                        }

                    } else {
                        $res = $this->wechatApp->user_tag->create($data['name']);
                        if (!$res) {
                            $this->error("服务端错误");
                        }
                        $data['tag_id'] = $res['tag']['id'];
                        $ck             = WxTag::create($data);
                        if ($ck !== false) {
                            $this->success("添加成功");
                        } else {
                            $this->error("添加失败");
                        }
                    }
                } catch (Exception $exception) {
                    $this->error($exception->getMessage());
                }

            }
            $wx_aid = Request::get('wx_aid');
            $view   = [
                'title' => lang('add'),
                'info'  => ['wx_aid' => $wx_aid],
            ];
            View::assign($view);

            return view('tag_add');
        }



        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: tagEdit
         * @describe: 编辑
         */
        public function tagEdit()
        {
            $id   = Request::get('id');
            $info = WxTag::find($id);

            $view = [
                'info'   => $info,
                'wx_aid' => $info['wx_aid'],
            ];
            View::assign($view);
            return view('tag_add');
        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: tagDel
         * @describe: 删除
         */
        public function tagDel()
        {
            $id   = Request::post('id');
            $info = WxTag::find($id);
            $res  = $this->wechatApp->user_tag->delete($info['tag_id']);
            if ($res['errcode'] == 0) {
                WxTag::destroy($id);
            } else {
                $this->error("删除失败");
            }
            $this->success("删除成功");

        }








        /**
         ************************历史消息管理***************************
         */

        /**
         * @return array|\think\response\View
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: message
         * @describe: 历史消息
         */
        public function message()
        {
            if (Request::isPost()) {
                $page  = Request::post('page') ? Request::post('page') : 1;
                $limit = Request::post('limit') ? Request::post('limit') : 10;
                $list  = Db::name('wx_msg_history')->where('store_id', $this->store_id)->where(
                    'wx_aid',
                    $this->wechatAccount->id
                )->order('id desc')->paginate(
                    ['list_rows' => $limit, 'page' => $page]
                )->toArray();

                return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total']];
            }

            return view();
        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: messageDel
         * @describe: 消息删除
         */
        public function messageDel()
        {
            if (Request::isPost()) {
                $id = Request::post('id');
                WxMsgHistory::destroy($id);
                $this->success("删除成功");
            }

        }



        /**
         * @return \think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: messageReply
         * @describe: 消息回复
         */
        public function messageReply()
        {
            if (Request::isPost()) {
                $material_id = Request::post('material_id');
                $openid      = Request::post('openid');
                $msg_type    = Request::post('msg_type');
                $material    = WxMaterial::find($material_id);
                if ($material) {
                    $media_id = $material->media_id;

                } else {
                    $media_id = '';
                }
                $message = WxReply::where($this->where)->where('type', 'default')->value('data');

                switch ($msg_type) {
                    case 'text':
                        $data    = Request::post('data');
                        $message = new Text($data);
                        break;

                    case 'image':
                        if (WxMaterial::where('media_id', $media_id)->find()) {

                            $message = new Image($media_id);
                        }
                        break;

                    case 'news':
                        $new = WxMaterialInfo::where($this->where)->where('material_id', $material_id)->find();
                        if ($new) {
                            $newsList[] = new NewsItem(
                                [
                                    'title'       => $new->title,
                                    'description' => $new->digest,
                                    'url'         => $new->url,
                                    'image'       => $new->cover,
                                ]
                            );
                            $message    = new News($newsList);
                        } else {
                            $message = WxReply::where($this->where)->where('type', 'default')->value('data');

                        }
                        break;
                    case 'video':
                        if (WxMaterial::where('media_id', $media_id)->find()) {
                            $message = new Video($media_id, $material->file_name, $material->des);
                        }
                        break;
                    case 'voice':
                        if (WxMaterial::where('media_id', $media_id)->find()) {

                            $message = new Voice($media_id);
                        }
                        break;
                    default:
                        break;
                }

                $result = $this->wechatApp->customer_service->message($message)->to($openid)->send();

                if ($result['errcode'] == 0) {
                    $this->success("发送成功");
                } else {
                    $this->error("发送失败");

                }
            } else {
                $id            = Request::get('id');
                $info          = WxMsgHistory::where('store_id', $this->store_id)->find($id);
                $user          = $this->wechatApp->user->get($info->openid);
                $materialGroup = $this->getMaterialGroup();
                $view          = [
                    'user'          => $user,
                    'info'          => $info,
                    'materialGroup' => $materialGroup,
                ];
                View::assign($view);

                return view();
            }

        }







        /**
         ************************素材管理***************************
         */


        /**
         * @return \think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: material
         * @describe: 素材
         */
        public function material()
        {
            $materialGroup = $this->getMaterialGroup();
            $view          = [
                'info'          => '',
                'materialGroup' => $materialGroup,
            ];

            View::assign($view);
            return view();
        }



        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: materialAdd
         * @describe:添加图文素材
         */
        public function materialAdd()
        {
            if (Request::isPost()) {
                $data = Request::post('content');

                foreach ($data as $k => $v) {
                    $article      = new Article($data[$k]);
                    $articles[$k] = $article;
                }
                $res = $this->wechatApp->material->uploadArticle($articles);
                $this->showError($res);
                $WxMaterialData = [
                    'store_id' => $this->store_id,
                    'wx_aid'   => $this->wechatAccount->id,
                    'type'     => 'news',
                    'media_id' => $res['media_id'],
                ];

                $material = $this->getMaterialByMediaId($res['media_id']);

                // 启动事务
                Db::startTrans();
                try {
                    $mat = WxMaterial::create($WxMaterialData);
                    //                if(isset($data[0])){
                    //多图文
                    foreach ($data as $k => $v) {

                        $data[$k]['cover']       = WxMaterial::where('media_id', $data[$k]['thumb_media_id'])->value(
                            'media_url'
                        );
                        $data[$k]['local_cover'] = WxMaterial::where('media_id', $data[$k]['thumb_media_id'])->value(
                            'local_cover'
                        );
                        $data[$k]['store_id']    = $this->store_id;
                        $data[$k]['wx_aid']      = $this->wechatAccount->id;
                        $data[$k]['url']         = $material['news_item'][$k]['url'];
                        $data[$k]['material_id'] = $mat->id;
                        $matinfo                 = Db::name('WxMaterialInfo')->save($data[$k]);
                    }
                    // 提交事务
                    Db::commit();
                    $this->success('成功');

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());

                }
            }
            $params['name']    = 'container';
            $params['content'] = '';
            $view              = [
                'info'    => [],
                'ueditor' => build_ueditor($params),
            ];
            View::assign($view);
            return view();
        }

        /**
         * @return \think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: materialEdit
         * @describe:
         */
        public function materialEdit()
        {
            if (Request::isPost()) {
                $data    = Request::post('content');
                $id      = Request::post('mediaId');
                $mediaId = WxMaterial::where('id', $id)->value('media_id');

                foreach ($data as $k => $v) {

                    $article = new Article($data[$k]);

                    $res = $this->wechatApp->material->updateArticle($mediaId, $article, $k);
                }
                $this->showError($res);

                $material = $this->getMaterialByMediaId($mediaId);

                // 启动事务
                Db::startTrans();
                try {
                    //
                    foreach ($data as $k => $v) {
                        $data[$k]['id']          = WxMaterialInfo::where($this->where)->where(
                            'thumb_media_id',
                            $v['thumb_media_id']
                        )->value('id');
                        $data[$k]['cover']       = WxMaterial::where('media_id', $data[$k]['thumb_media_id'])->value(
                            'media_url'
                        );
                        $data[$k]['store_id']    = $this->store_id;
                        $data[$k]['wx_aid']      = $this->wechatAccount->id;
                        $data[$k]['url']         = $material['news_item'][$k]['url'];
                        $data[$k]['material_id'] = $id;
                        $data[$k]['update_time'] = time();
                        $WxMaterialInfoModel     = WxMaterialInfo::find($data[$k]['id']);
                        $r[$k]                   = $WxMaterialInfoModel->force()->save($data[$k]);
                    }

                    // 提交事务
                    Db::commit();
                    $this->success('成功');

                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
            }
            $id                = Request::get('id');
            $info              = WxMaterialInfo::where('material_id', $id)->select()->toArray();
            $params['name']    = 'container';
            $params['content'] = '';
            $view              = [
                'title'   => lang('edit'),
                'info'    => $info,
                'ueditor' => build_ueditor($params),
            ];
            View::assign($view);

            return view('material_add');
        }



        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: materialAysn
         * @describe: 素材同步
         */
        public function materialAysn()
        {
            if (Request::isPost()) {
                $res = cache('materialList');
                if (!$res) {
                    $res = $this->wechatApp->material->list('news', 0, 50);
                    cache('materialList', $res, 3600);
                }
                $this->showError($res);
                foreach ($res['item'] as $k => $v) {
                    $material = WxMaterial::where('media_id', $v['media_id'])->find();
                    if (!$material) {
                        $material = [
                            'store_id'  => $this->store_id,
                            'wx_aid'    => $this->wechatAccount->id,
                            'media_id'  => $v['media_id'],
                            'media_url' => $v['content']['news_item'][0]['thumb_url'],
                            'type'      => "news",
                        ];
                        $wxmater  = WxMaterial::create($material);
                        foreach ($v['content']['news_item'] as $kk => $vv) {
                            $info = [
                                'store_id'              => $this->store_id,
                                'wx_aid'                => $this->wechatAccount->id,
                                'material_id'           => $wxmater->id,
                                'thumb_media_id'        => $vv['thumb_media_id'],
                                'local_cover'           => $vv['thumb_url'],
                                'cover'                 => $vv['thumb_url'],
                                'title'                 => $vv['title'],
                                'author'                => $vv['author'],
                                'show_cover'            => $vv['show_cover_pic'],
                                'digest'                => $vv['digest'],
                                'content'               => $vv['content'],
                                'url'                   => $vv['url'],
                                'content_source_url'    => $vv['content_source_url'],
                                'need_open_comment'     => $vv['need_open_comment'],
                                'only_fans_can_comment' => $vv['only_fans_can_comment'],
                            ];
                            WxMaterialInfo::create($info);

                        }
                    }
                }
                $this->success(lang('aysn success'));

            } else {

                $this->error(lang('invalid request'));
            }


        }

        /**
         * @throws Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: materialDel
         * @describe:
         */
        public function materialDel()
        {

            $id       = Request::post('id');
            $material = WxMaterial::find($id);
            //删除微信媒体库
            $this->wechatApp->material->delete($material->media_id);

            if ($material['type'] == 'news') {
                $info = WxMaterialInfo::where($this->where)->where('material_id', $id)->delete();
                if ($info && $material->delete()) {
                    $this->success("删除成功");
                } else {
                    $this->error("删除失败");

                }
            } else {
                if ($material->delete()) {
                    $this->success("删除成功");
                } else {
                    $this->error("删除失败");

                }
            }

        }



        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: materialSend
         * @describe: 发送消息
         */
        public function materialSend()
        {
            if (Request::isPost()) {
                $id   = Request::post('id');
                $info = WxMaterial::find($id);
                $res  = $this->sendAll($info);
                $this->showError($res);
                $this->success("发送成功");
            } else {
                $this->error("发送失败");

            }

        }



        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: materialPreview
         * @describe: 预览消息
         */
        public function materialPreview()
        {
            if (Request::isPost()) {
                $wxname = Request::post('wxname');
                $id     = Request::post('id');
                $info   = WxMaterial::find($id);
                $res    = $this->preview($info, $wxname);

                $this->showError($res);
                $this->success(lang('send success'));
            } else {
                $this->error(lang('send fail'));

            }


        }

        /**
         * @param $info
         * @param $wxname
         * @return mixed
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: preview
         * @describe:
         */
        protected function preview($info, $wxname)
        {
            // 发送预览群发消息给指定的 openId 用户
            //$this->wechatApp->broadcasting->previewText($text, $openId);
            //$this->wechatApp->broadcasting->previewNews($mediaId, $openId);
            //$this->wechatApp->broadcasting->previewVoice($mediaId, $openId);
            //$this->wechatApp->broadcasting->previewImage($mediaId, $openId);
            //$this->wechatApp->broadcasting->previewVideo($message, $openId);
            //$this->wechatApp->broadcasting->previewCard($cardId, $openId);
            //发送预览群发消息给指定的微信号用户
            //$wxanme 是用户的微信号，比如：notovertrue
            //
            //$this->wechatApp->broadcasting->previewTextByName($text, $wxname);
            //$this->wechatApp->broadcasting->previewNewsByName($mediaId, $wxname);
            //$this->wechatApp->broadcasting->previewVoiceByName($mediaId, $wxname);
            //$this->wechatApp->broadcasting->previewImageByName($mediaId, $wxname);
            //$this->wechatApp->broadcasting->previewVideoByName($message, $wxname);
            //$this->wechatApp->broadcasting->previewCardByName($cardId, $wxname);

            $type = $info->type;
            switch ($type) {
                case 'text':
                    $res = $this->wechatApp->broadcasting->previewTextByName($info->media_id, $wxname);
                    break;

                case 'image':

                    $res = $this->wechatApp->broadcasting->previewImageByName($info->media_id, $wxname);

                    break;

                case 'news':
                    $res = $this->wechatApp->broadcasting->previewNewsByName($info->media_id, $wxname);

                    break;
                case 'video':
                    $res = $this->wechatApp->broadcasting->previewVideoByName($info->media_id, $wxname);


                    break;
                case 'voice':
                    $res = $this->wechatApp->broadcasting->previewVoiceByName($info->media_id, $wxname);
                    break;
                case 'card':
                    $res = $this->wechatApp->broadcasting->previewCardByName($info->media_id, $wxname);
                    break;
                default:
                    $res = $this->wechatApp->broadcasting->previewTextByName($info->media_id, $wxname);

                    break;
            }

            return $res;

        }

        /**
         * @param $info
         * @return mixed
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: sendAll
         * @describe:
         */
        protected function sendAll($info)
        {
            $type = $info->type;
            switch ($type) {

                case 'image':
                    $res = $this->wechatApp->broadcasting->sendImage($info->media_id);
                    break;
                case 'news':
                    $res = $this->wechatApp->broadcasting->sendNews($info->media_id);
                    break;
                case 'video':
                    $res = $this->wechatApp->broadcasting->sendVideo($info->media_id);
                    break;
                case 'voice':
                    $res = $this->wechatApp->broadcasting->sendVoice($info->media_id);
                    break;
                case 'card':
                    $res = $this->wechatApp->broadcasting->sendCard($info->media_id);
                    break;
                default:
                    $res = $this->wechatApp->broadcasting->image($info->media_id);
                    break;
            }

            return $res;

        }







        /**
         ************************二维码设置**************************
         */


        /**
         * @return array|\think\response\View
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: qrcode
         * @describe:
         */
        public function qrcode()
        {
            if (Request::isPost()) {
                $page  = Request::post('page') ? Request::post('page') : 1;
                $limit = Request::post('limit') ? Request::post('limit') : 10;
                $list  = Db::name('wx_qrcode')->order('id desc')->paginate(
                    ['list_rows' => $limit, 'page' => $page]
                )->toArray();

                return $result = [
                    'code'  => 0,
                    'msg'   => 'ok',
                    'data'  => $list['data'],
                    'count' => $list['total'],
                ];
            }

            return view();
        }

        /**
         * @return \think\response\View
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: qrcodeAdd
         * @describe:
         */
        public function qrcodeAdd()
        {
            if (Request::isPost()) {
                $data = Request::param();
                if ($data['type'] == 0) {
                    $data['expire_seconds'] = $data['expire_seconds'] ? $data['expire_seconds'] : 2592000;
                    $res                    = $this->wechatApp->qrcode->temporary('foo', $data['expire_seconds']);
                } else {
                    $res = $this->wechatApp->qrcode->forever('foo');
                }
                $this->showError($res);
                $data['store_id'] = $this->wechatAccount->id;
                $data['wx_aid']   = $this->store_id;
                $data['ticket']   = $res['ticket'];
                $data['url']      = $res['url'];
                $data['qrcode']   = $url = $this->wechatApp->qrcode->url($res['ticket']);
                if (Db::name('wx_qrcode')->insert($data)) {
                    $this->success("添加成功");
                } else {
                    $this->error("添加失败");
                }
            }

            return view();
        }



        /**
         * @return \think\response\View
         * @throws Exception
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: qrcodeState
         * @describe:
         */
        public function qrcodeState()
        {
            if (Request::isPost()) {
                $id     = Request::param('id');
                $qr     = Db::name('wx_qrcode')->find($id);
                $status = $qr['status'] == 1 ? 0 : 1;

                $res = Db::name('wx_qrcode')->where('id', $qr['id'])->update(['status' => $status]);
                if ($res) {
                    $this->success("操作成功");
                } else {
                    $this->error("操作失败");
                }
            }
            $view = [
                'info'  => '',
            ];
            View::assign($view);
            return view();
        }




        /**
         * @throws Exception
         * @throws \think\exception\PDOException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: qrcodeDel
         * @describe:
         */
        public function qrcodeDel()
        {
            if (Request::isPost()) {
                $id  = Request::param('id');
                $res = Db::name('wx_qrcode')->delete($id);
                if ($res) {
                    $this->success("删除成功");
                } else {
                    $this->error("删除失败");
                }
            }
        }











        /**
         ************************回复设置***************************
         */
        public function reply()
        {
            $type     = Request::get('type', 'default');
            $typeList = [
                [
                    'url'  => "/wechat/wechat/reply?type=default",
                    'item' => "默认回复",
                    "type" => 'default',
                ],
                [
                    'url'  => "/wechat/wechat/reply?type=subscribe",
                    'item' => "关注回复",
                    "type" => 'subscribe',
                ],

                [
                    'url'  => "/wechat/wechat/reply?type=keyword",
                    'item' => "关键字回复",
                    "type" => 'keyword',
                ],

            ];

            if ($type == 'default') {

                $info = Db::name('wx_reply')->where($this->where)->where('type', $type)->select();
            } elseif ($type == 'subscribe') {
                $info = Db::name('wx_reply')->where($this->where)->where('type', $type)->select();

            } elseif ($type == 'keyword') {
                $info = Db::name('wx_reply')->where($this->where)->where('type', $type)->select();
            }

            $view = [
                'type'     => $type,
                'info'     => $info,
                'typeList' => $typeList,
            ];
            View::assign($view);

            return view();


        }

        /**
         * @return \think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: replyAdd
         * @describe:
         */
        public function replyAdd()
        {
            if (Request::isPost()) {
                $data             = Request::post();
                $data['store_id'] = $this->store_id;
                $data['wx_aid']   = $this->wechatAccount->id;
                if (!$data['type']) {
                    $data['type'] = 'keyword';
                }
                if ($data['data']) {
                    $data['msg_type'] = 'text';
                }
                $res = WxReply::create($data);
                if ($res) {
                    $this->success("回复成功", url('index'));
                } else {
                    $this->error("回复失败");
                }
            }
            $type = Request::get('type', 'default');

            $view = [
                'info'          => ['type' => $type],
                'type'          => $type,
                'materialGroup' => $this->getMaterialGroup(),

            ];
            View::assign($view);

            return view();

        }

        /**
         * @return \think\response\View
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: replyEdit
         * @describe:
         */
        public function replyEdit()
        {
            if (Request::isPost()) {
                $data             = Request::post();
                $data['store_id'] = $this->store_id;
                $data['wx_aid']   = $this->wechatAccount->id;
                $res              = WxReply::update($data);
                if ($res) {
                    $this->success("编辑成功", url('index'));
                } else {
                    $this->error("编辑失败");
                }
            }
            $info = WxReply::find(Request::get('id'));
            $view = [
                'info'          => $info,
                'materialGroup' => $this->getMaterialGroup(),
            ];
            View::assign($view);
            return view('reply_add');

        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: replyDel
         * @describe:
         */
        public function replyDel()
        {
            $id = Request::post('id');
            WxReply::destroy($id);
            $this->success("删除成功");

        }





        /**
         ************************接口返回***************************
         */


        /**
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: getMaterialByType
         * @describe:获取素材
         */
        public function getMaterialByType()
        {
            $type = Request::post('type');
            //      $type text 素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）

            //      $res = $this->wechatApp->material->list($type,0,100);
            $res = WxMaterial::where($this->where)->where('type', $type)->where($this->where)->select()->toArray();
            if ($type == 'news') {
                foreach ($res as $k => $v) {
                    $res[$k]['groupList'] = WxMaterialInfo::where($this->where)->where('material_id', $v['id'])->select(
                    )->toArray();
                }
            }
            $this->success(lang('get info success'), '', $res);


        }


        /**
         * @return array
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: getMaterialGroup
         * @describe:
         */
        protected function getMaterialGroup()
        {
            $materialGroup = [];
            foreach ($this->materialType as $k => $v) {
                if ($v == 'news') {

                    $weixin_material_info = Db::name('wx_material')->where('type', 'news')->select();
                    if (!empty($weixin_material_info)) {
                        foreach ($weixin_material_info as $key => $value) {

                            $item_info                               = Db::name('wx_material_info')->where(
                                'material_id',
                                $value['id']
                            )->select();
                            $weixin_material_info[$key]['item_info'] = $item_info;
                        }
                    }
                    $materialGroup[$v] = $weixin_material_info;

                } else {
                    $weixin_material_info = Db::name('wx_material')->where('type', $v)->select();
                    $materialGroup[$v] = $weixin_material_info;

                }
            }

            return $materialGroup;

        }





        /**
         ********************************上传素材接口***************************************
         */


        /**
         * @return false|mixed|string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/11
         * @name: UpVideo
         * @describe:
         */
        public function UpVideo()
        {
            if ($_POST) {
                $file = Request::file("file");

                $info = $file->validate(
                    ['size' => 1 * 1024 * 1024 * 1024, 'ext' => "mp4,flv,3gp,mov,avi,rmvb,mkv,wmv"]
                )->move(ROOT_PATH.'public'.DS_PROS.'upload'.DS_PROS."video");

                if ($info) {
                    $path = '/upload'.DS_PROS."video".DS_PROS.$info->getSaveName();

                    $path = str_replace("\\", "/", $path);

                    return json_encode(["code" => 1, "URL" => $path, "msg" => '上传成功']);
                } else {

                    return json_encode(["code" => 0, "msg" => "上传有误，请检查服务器配置！"]);
                }
            }

            return $this->fetch();
        }



        /**
         * @param $type
         * @return mixed
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: uploads
         * @describe:
         */
        protected function uploads($type)
        {
            //获取上传文件表单字段名
            $fileKey = array_keys(request()->file());
            for ($i = 0; $i < count($fileKey); $i++) {
                //获取表单上传文件
                $file = request()->file($fileKey[$i]);
                try {
                    $info = $file->move(ROOT_PATH.'public'.DS_PROS.'uploads'.DS_PROS."wechat");
                    if ($info) {
                        $path[] = '/uploads'.DS_PROS."wechat".DS_PROS.$info->getSaveName();
                    }
                } catch (\think\exception\ValidateException $e) {
                    $path  = '';
                    $error = $e->getMessage();
                }
            }
            if (!empty($path)) {
                $result['code'] = 1;
                //分辨是否截图上传，截图上传只能上传一个，非截图上传可以上传多个
                if (Request::param('responseType') == 'json') {
                    $result["url"] = $path[0];
                } else {
                    $result["url"] = $path[0];
                }
                $result['msg'] = "上传成功";

                return $result;
            } else {
                //上传失败获取错误信息
                $result['url']  = '';
                $result['msg']  = $error;
                $result['code'] = 0;

                return $result;
            }

        }



        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: imageUpload
         * @describe:
         */
        public function imageUpload()
        {

            $res = $this->uploads($this->imageValidate);
            if ($res['code'] > 0) {
                //路劲用相对路径
                $result = $this->wechatApp->material->uploadImage('./'.$res['url']);
                $this->showError($result);
                $data = [
                    'store_id'    => $this->store_id,
                    'wx_aid'      => $this->wechatAccount->id,
                    'media_id'    => $result['media_id'],
                    'media_url'   => $result['url'],
                    'local_cover' => $res['url'],
                    'type'        => 'image',
                ];

                $r = WxMaterial::create($data);
                if ($r) {
                    $this->success("上传成功", '', $result);
                } else {
                    $this->error('上传失败');

                }
            } else {
                $this->error('上传失败');

            }
        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: videoUpload
         * @describe:
         */
        public function videoUpload()
        {
            $data = Request::post();
            if (!$data['url'] || !$data['file_name'] || !$data['des']) {
                $this->error('数据不能为空');
            }
            $result = $this->wechatApp->material->uploadVideo('.'.$data['url'], $data['file_name'], $data['des']);
            $this->showError($result);
            $resource      = $this->wechatApp->material->get($result['media_id']);
            $datas         = [
                'store_id'    => $this->store_id,
                'wx_aid'      => $this->wechatAccount->id,
                'media_id'    => $result['media_id'],
                'media_url'   => $resource['down_url'],
                'local_cover' => $data['url'],
                'type'        => 'video',
                'file_name'   => $data['file_name'],
                'des'         => $data['des'],
            ];
            $result['url'] = $resource['down_url'];

            $r = WxMaterial::create($datas);
            if ($r) {
                $this->success("上传成功", '', $result);
            } else {
                $this->error('上传失败');

            }


        }

        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: voiceUpload
         * @describe:
         */
        public function voiceUpload()
        {
            $res = $this->uploads($this->voiceValidate);
            if ($res['code'] > 0) {
                //路劲用相对路径
                $result = $this->wechatApp->material->uploadVoice('./'.$res['url']);
                $this->showError($result);
                $resource = $this->wechatApp->material->get($result['media_id']);

                $data          = [
                    'store_id'    => $this->store_id,
                    'wx_aid'      => $this->wechatAccount->id,
                    'media_id'    => $result['media_id'],
                    'media_url'   => $resource['down_url'],
                    'local_cover' => $res['url'],

                    'type' => 'image',
                ];
                $result['url'] = $resource['down_url'];
                $r             = WxMaterial::create($data);
                if ($r) {
                    $this->success("上传成功", '', $result);
                } else {
                    $this->error('上传失败');

                }
            } else {
                $this->error('上传失败');

            }

        }


        /**
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: thumbUpload
         * @describe:
         */
        public function thumbUpload()
        {
            $res = $this->uploads($this->thumbValidate);
            if ($res['code'] > 0) {
                //路劲用相对路径
                $result = $this->wechatApp->material->uploadThumb('./'.$res['url']);
                $this->showError($result);
                $data = [
                    'store_id'    => $this->store_id,
                    'wx_aid'      => $this->wechatAccount->id,
                    'media_id'    => $result['media_id'],
                    'media_url'   => $result['url'],
                    'local_cover' => $res['url'],
                    'type'        => 'image',
                ];

                $r = WxMaterial::create($data);
                if ($r) {
                    $this->success("上传成功", $result['url']);
                } else {
                    $this->error("上传失败");

                }
            } else {
                $this->error("上传失败");

            }


        }

        /**
         * @return false|string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: UeditUploadImage
         * @describe:
         */
        public function UeditUploadImage()
        {

            $res = $this->uploads($this->imageValidate);
            if ($res['code'] > 0) {
                //路劲用相对路径
                $result = $this->wechatApp->material->uploadImage('./'.$res['url']);
                $this->showError($result);
                $data = [
                    'store_id'    => $this->store_id,
                    'wx_aid'      => $this->wechatAccount->id,
                    'media_id'    => $result['media_id'],
                    'media_url'   => $result['url'],
                    'local_cover' => $res['url'],
                    'type'        => 'image',
                ];

                $r    = WxMaterial::create($data);
                $data = ['state' => 'SUCCESS', 'url' => $data['media_url']];

            } else {
                $data = ['state' => 'SUCCESS', 'url' => ''];

            }
            return json_encode($data);
        }


        /**
         * @return false|string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: UeditUploadVideo
         * @describe:
         */
        public function UeditUploadVideo()
        {
            $res = $this->uploads($this->videoValidate);

            if ($res['code'] > 0) {
                //路劲用相对路径
                $result = $this->wechatApp->material->uploadVideo('./'.$res['url'], $res['url'], $res['url']);
                $this->showError($result);
                $resource = $this->wechatApp->material->get($result['media_id']);

                $data          = [
                    'store_id'    => $this->store_id,
                    'wx_aid'      => $this->wechatAccount->id,
                    'media_id'    => $result['media_id'],
                    'media_url'   => $resource['down_url'],
                    'local_cover' => $res['url'],
                    'type'        => 'video',
                    'file_name'   => $res['url'],
                    'des'         => $res['url'],
                ];
                $result['url'] = $resource['down_url'];
                $r             = WxMaterial::create($data);

                $data = ['state' => 'SUCCESS', 'url' => $resource['down_url']];
            } else {
                $data = ['state' => 'SUCCESS', 'url' => ''];

            }

            return json_encode($data);

        }


        /**
         * @return false|string
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: UeditUploaVoice
         * @describe:
         */
        public function UeditUploaVoice()
        {

            $res = $this->uploads($this->voiceValidate);

            if ($res['code'] > 0) {
                //路劲用相对路径
                $result = $this->wechatApp->material->uploadVoice('./'.$res['url']);
                $this->showError($result);
                $resource = $this->wechatApp->material->get($result['media_id']);

                $data          = [
                    'store_id'    => $this->store_id,
                    'wx_aid'      => $this->wechatAccount->id,
                    'media_id'    => $result['media_id'],
                    'media_url'   => $resource['down_url'],
                    'local_cover' => $res['url'],
                    'type'        => 'image',
                ];
                $result['url'] = $resource['down_url'];
                $r             = WxMaterial::create($data);

                $data = ['state' => 'SUCCESS', 'url' => $resource['down_url']];
            } else {
                $data = ['state' => 'SUCCESS', 'url' => ''];
            }
            return json_encode($data);
        }



        /**
         * @return false|string
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: getListImage
         * @describe:
         */
        public function getListImage()
        {
            $list = WxMaterial::where($this->where)->where('type', 'image')->select();
            $data = ['state' => 'SUCCESS', 'start' => 0, 'total' => count($list), 'list' => []];
            if ($list) {
                foreach ($list as $k => $v) {
                    $data['list'][$k]['url']   = $v['media_url'];
                    $data['list'][$k]['mtime'] = time();
                }
            }
            return json_encode($data);
        }




        /**
         * @param $res
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: showError
         * @describe:微信返回数据
         */
        protected function showError($res)
        {
            if (isset($res['errcode']) && $res['errcode'] > 0) {
                $this->error($res['errmsg']);
            }

        }




        /**
         * @param $mediaId
         * @return mixed
         * @author: LuckyHhy <jackhhy520@qq.com>
         * @date: 2020/3/20
         * @name: getMaterialByMediaId
         * @describe:获取媒体素材
         */
        protected function getMaterialByMediaId($mediaId)
        {
            $resource = $this->wechatApp->material->get($mediaId);
            $this->showError($resource);
            return $resource;

        }



    }